from plugin import plugin
import plugins, inspect, commands

__doc__ = "admin"

class admin(plugin):
	"Provides things to administer :O"
	
	def __init__(self):
		self._version = '3.0 stable'

	@plugins.irc_throw
	def auth(self, msg, args):
		"Allows you to auth yourself as admin, if you know the password!"
		if msg['sender']['admin']:
			return 'Error! You are already an admin!'

		if args == 'changeme':
			self._irc.add_admin(msg['sender']['name'])
			self._irc.privmsg(msg['channel'], msg['sender']['name'] + ': You were successfully authed!')
		else:
			self._irc.privmsg(msg['channel'], msg['sender']['name'] + ': Wrong password')

	def load(self, msg, args):
		"Admin command! Allows admins to load modules."
		if msg['sender']['admin']:
			result = 'Success!'
			res = __import__(args, globals(), locals(), [args], -1)
			if not res: result = 'Failed!'
			reload(res)
			self._irc.privmsg(msg['channel'], 'Loading module: ' + args + ' ..' + result)
		else:
			self._throw_auth_error(msg)

	def reload(self, msg, args):
		"Admin command! Allows admins to reload modules."
		if msg['sender']['admin']:
			if args == '*':
				self._irc.privmsg(msg['channel'], 'Reloading all modules')
				for mod in self.plugins:
					reload(inspect.getmodule(mod))
					__import__(args, globals(), locals(), [args], -1)
			else:
				result = 'Failed!'
				if args in self._mods:
					reload(inspect.getmodule(self._mods[args]))
					__import__(args, globals(), locals(), [args], -1)
					result = 'Success!'
				self._irc.privmsg(msg['channel'], 'Reloading module: ' + args + ' ..' + result)
		else:
			self._throw_auth_error(msg)

	@plugins.irc_throw
	def unload(self, msg, args):
		"Admin command! Allows admins to unload modules."
		if msg['sender']['admin']:
			if args == 'core':
				return 'You cant unload core!'

			result = 'Failed!'
			mods = self._mods
			for mod in mods:
				if mod == args:
					self.plugins.remove(mods[mod])
					result = 'Success!'
					break
			self._irc.privmsg(msg['channel'], 'Unloading module: ' + args + ' ..' + result)
		else:
			self._throw_auth_error(msg)

	def nick(self, msg, args):
		"Admin command! Allows admins to change my name."
		if msg['sender']['admin']:
			self._irc.nick(args)
		else:
			self._throw_auth_error(msg)

	def join(self, msg, args):
		"Admin command! Allows admins to make me join a channel."
		if msg['sender']['admin']:
			self._irc.join(args)
		else:
			self._throw_auth_error(msg)

	def part(self, msg, args):
		"Admin command! Allows admins to make me leave a channel."
		if msg['sender']['admin']:
			self._irc.part(args)
		else:
			self._throw_auth_error(msg)

	def hg(self, msg, args):
		"Admin command! Allows admins to make me do hg stuff."
		if not msg['sender']['admin']:
			self._throw_auth_error(msg)
			return
		data = commands.getoutput('hg ' + args)
		for line in data.split('\n'):
			self._irc.reply(msg, line)
		

	def _throw_auth_error(self, msg):
		self._irc.reply(msg, 'You are not admin!')
